package com.anxin.security.util;

import com.anxin.system.dto.UserInfoDTO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;

@Component
public class SecurityUtils{

    private final RedisTemplate<String, Object> redisTemplate;

    public SecurityUtils(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取当前登录用户的 UserInfoDTO, 判断是否登录, 如果未登录则抛出异常
     * @return UserInfoDTO
     */
    public UserInfoDTO getCurrentUserInfo() {
        HttpServletRequest request = getCurrentRequest();

        String token = extractToken(request);
        String redisKey = "user:auth:" + token;

        Object userObj = redisTemplate.opsForValue().get(redisKey);
        if (!(userObj instanceof UserInfoDTO userInfo)) {
            throw new RuntimeException("登录状态异常");
        }

        return userInfo;
    }

    /**
     * 获取当前请求对象
     */
    private HttpServletRequest getCurrentRequest() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        if (ra == null) {
            throw new RuntimeException("当前线程未绑定请求上下文");
        }
        return ((ServletRequestAttributes) ra).getRequest();
    }

    /**
     * 提取 Token
     */
    private String extractToken(HttpServletRequest request) {
        String auth = request.getHeader("Authorization");
        if (auth == null || !auth.startsWith("Bearer ")) {
            throw new RuntimeException("未登录");
        }
        return auth.substring(7); // 去掉 Bearer 前缀
    }
}
